import { Middleware, IMiddleware, Inject, Config } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { CacheManager } from '@midwayjs/cache';
import { Context, NextFunction } from '@midwayjs/koa';
import { CustomHttpError } from '../common/CustomHttpError';
import { HttpStatus } from '@midwayjs/core';

@Middleware()
export class AuthorityMiddleware implements IMiddleware<Context, NextFunction> {
  @Inject()
  jwt: JwtService;
  @Inject()
  cache: CacheManager;
  @Config('jwt')
  config;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const { url } = ctx;

      if (/.*open.*/.test(url)) {
        return await next();
      }

      // 获取token
      let token = ctx.get('Authorization');
      if (token.includes('Bearer ')) {
        token = token.split('Bearer ')?.[1];
      }
      // 没传token抛出异常
      if (!token) {
        throw new CustomHttpError(
          'token已过期或未授权',
          HttpStatus.UNAUTHORIZED
        );
      }
      try {
        const { secret } = this.config;

        // 校验token是否合法
        const user: any = await this.jwt.verify(token, secret);

        // // 从缓存中获取当前用户接口权限信息
        // const perms: string[] = await this.cache.get(
        //   `es:admin:perms:${user.id}`
        // )
        // 判断是否存在当前接口权限
        // if (perms && !perms.includes(url)) {
        //   throw new CustomHttpError('无权限访问~', 1001)
        // }
        ctx.user = user;

        await next();
      } catch (error) {
        throw new CustomHttpError(error.message, HttpStatus.UNAUTHORIZED);
      }
    };
  }
}
